<template>
  <div>
    <t-upload
      ref="upload"
      :action="action"
      v-model="files"
      :disabled="disabled"
      :autoUpload="autoUpload"
      :locale="locale"
      theme="image"
      accept="video/*"
      @fail="handleFail"
      @success="handleSuccess"
      :multiple="multiple"
      :showUploadProgress="false"
      :beforeUpload="beforeUpload"
      :formatRequest="formatRequest"
      :formatResponse="formatImgResponse"
      :imageViewerProps="imageViewerProps"
      :showImageFileName="showImageFileName"
    ></t-upload>
  </div>
</template>

<script>
import {tencentCosAuthApi} from "@/api/common";

export default {
  name: 'UploadVideo',
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    module: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: '',
      files: [],
      autoUpload: true,
      showImageFileName: false,
      imageViewerProps: {
        closeOnEscKeydown: false,
      },
      action: '',
      sizeLimit: 99,
      list: [],
      fileDataList: [],
      current: 0,  // 当前上传的图片索引
      locale: {
        triggerUploadText: { image: '上传视频', normal: '点击上传', fileInput: '选择文件', reupload: '重新上传', delete: '删除', continueUpload: '继续选择' }
      },
    }
  },
  methods: {
    formatImgResponse(err, res) {
      if (err) {
        return { error: '网络异常，图片上传失败' };
      } else {
        return { url: res.file.src };
      }
    },
    // 一旦 formatResponse 返回值包含 error，便会被组件判定为上传失败
    formatResponse() {
      return { error: '网络异常，图片上传失败' };
    },
    handleSuccess(context) {
      this.$emit('success', context)
      //this.files = context.response
    },
    handleFail({ file }) {
      this.$message.error(`文件 ${file.name} 上传失败`);
    },
    formatRequest(file) {
      const params = {
        ...this.fileDataList[this.current],
        file: file.file,
      }
      this.current ++
      return params;
    },
    // 文件上传前
    async beforeUpload(file) {
      // 文件大小限制5M
      const isLt5M = file.size / 1024 / 1024 < this.sizeLimit
      if (!isLt5M) {
        this.$message.error(`上传图片大小不能超过 ${this.sizeLimit}MB!`)
        return false
      }
      try {
        const params = {
          file_name: file.name,
          file_module: this.module
        }
        const res = await tencentCosAuthApi(params)
        let { data, url, src } = res;
        this.action = url;
        file.src = src
        this.list.push({ url: src });
        data.success_action_status = 200;
        this.fileDataList.push(data);
        return true;
      } catch (err) {
        this.$message.error(`文件 ${file.name} 文件上传失败`);
        return false
      }
    }
  }
}
</script>

<style lang="less" scoped>

</style>
